from flask import Flask,request
from wblogin.login import get_session
from db.dbbase import DBBase
from multiprocessing import Pool
from searchtask.search import search_keyword
from wblogin.wxlogin import wx_login
import time
#from page_parse.wxparse import hand_source
from page_parse.wxparse import hand_source
app = Flask(__name__)
'''
微博登陆接口
'''
@app.route('/spider/weibo/login',methods=['POST','GET'])
def wb_login():
    us = request.form.get('us')
    pw = request.form.get('pw')
    adminid = request.form.get('adminid')
    wbsession = get_session(us,pw)
    if wbsession is not None:
        dbbase = DBBase()
        wb_session = wbsession.cookies.get_dict()
        result_int = dbbase.insert_wb_usercount(adminid=adminid,wb_us=us,wb_pw=pw,wb_cookies=str(wb_session))
        return str(result_int)# 登陆成功
    return '21100'# 登陆失败
'''
微博搜索关键字提交接口
'''
@app.route('/spider/weibo/keyword',methods=['POST','GET'])
def wb_keyword():
    usercountID = request.form.get('usercountID')
    keyword = request.form.get('keyword')
    adminid = request.form.get('adminid')
    p = Pool()
    p.apply_async(func=async_search_keyword,args=(usercountID, keyword, adminid))
    return '21100'
'''
微博采集数据 异步进行
'''
def async_search_keyword(usercountID, keyword, adminid):
    dbbase = DBBase()
    wb_cookie_data = dbbase.find_wbcookies_byid(usercountID)
    cookies = wb_cookie_data['wb_cookies']
    wb_username = wb_cookie_data['wb_us']
    name_cookies = [wb_username, eval(cookies)]
    # 异步执行
    print(keyword)
    search_keyword(keyword=keyword, name_cookies=name_cookies, adminid=adminid)
'''
微博采集信息查询
'''
@app.route('/spider/weibo/getdata',methods=['POST','GET'])
def wb_getdata():
    pageIndex = request.form.get('pageIndex')
    keyword = request.form.get('c_name').strip()
    dbbase = DBBase()
    result_json = ''
    if keyword == '':
        keyword = None
    data_cursor = dbbase.find_wb(pageIndex,keyword)
    total = data_cursor.count(with_limit_and_skip=False)# 获取总页数
    pagecount = int((total + 10 - 1) / 10)
    for wx in data_cursor:
        result_json = result_json + str(wx) + ','
    data = '[' + result_json + ']'
    return "{'datasource':" + data + ",'total':" + str(total) +",'pagecount':"+ str(pagecount) + "}"

'''
微信登陆接口
'''
@app.route('/spider/weixin/login',methods=['POST','GET'])
def wx_login_api():
    adminid = request.form.get('adminid')
    requstuuid = request.form.get('requstuuid')
    wx_login(adminid, requstuuid)
    return '221100'

'''
获取微信登陆二维码接口
'''
@app.route('/spider/weixin/getqcode', methods=['POST', 'GET'])
def wx_login2():
    adminid = request.form.get('adminid')
    requstuuid = request.form.get('requstuuid')
    dbbase = DBBase()
    flag = True
    data = ''
    while flag:
        data = dbbase.find_wxqcode_byid(adminid, requstuuid)
        if data is not None:
            flag = False
        time.sleep(0.2)
    data_str = "'adminid':'{}','codeurl':'{}','requstuuid':'{}'".format(
        data['adminid'],data['codeurl'],data['requstuuid'])
    return '{' + data_str + '}'
'''
微信登陆检测接口
'''
@app.route('/spider/weixin/login/check',methods=['POST','GET'])
def wx_login_check():

    requstuuid = request.form.get('requstuuid')
    adminid = request.form.get('adminid')

    dbbase = DBBase()
    cookies = dbbase.find_wxcookies_by(adminid,requstuuid)
    if cookies is None:
        return 'fail'
    cookie = cookies['cookies']
    if cookie == 0:
        return 'fail'
    return 'success'

'''
微信搜索关键字提交接口
'''
@app.route('/spider/weixin/keyword',methods=['POST','GET'])
def wx_keyword():

    requstuuid = request.form.get('requstuuid')
    keyword = request.form.get('keyword')
    adminid = request.form.get('adminid')

    dbbase = DBBase()
    cookies = dbbase.find_wxcookies_by(adminid,requstuuid)['cookies']
    p = Pool()
    p.apply_async(func=hand_source, args=(adminid, keyword,cookies))

    return 'success'
'''
微信采集信息查询
'''
@app.route('/spider/weixin/getdata',methods=['POST','GET'])
def wx_getdata():
    pageIndex = request.form.get('pageIndex')
    keyword = request.form.get('c_name').strip()
    dbbase = DBBase()
    result_json = ''
    if keyword == '':
        keyword = None
    data_cursor = dbbase.find_wx(pageIndex,keyword)
    total = data_cursor.count(with_limit_and_skip=False)# 获取总页数
    pagecount = int((total + 10 - 1) / 10)
    for wx in data_cursor:
        result_json = result_json + str(wx) + ','
    data = '[' + result_json + ']'
    return "{'datasource':" + data + ",'total':" + str(total) +",'pagecount':"+ str(pagecount) + "}"
'''
测试接口
'''
@app.route('/spider/test', methods=['POST', 'GET'])
def test():
    print('test')
    time.sleep(10)
    return 'test'


if __name__ == '__main__':
    app.run(debug=True,threaded=True)
